package xiang.weiyu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import xiang.weiyu.common.R;
import xiang.weiyu.pojo.Category;
import xiang.weiyu.service.CategoryService;

import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CateporyController {
    @Autowired
    private CategoryService categoryService;

    /**
     * 新增
     *
     * @param category
     * @return R<String>
     */
    @PostMapping
    public R<String> insert(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("新增菜品分类成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return R<Page>
     */
    @GetMapping("/page")
    public R<Page> selectpage(int page, int pageSize) {
        Page<Category> pageInfo = new Page<>(page, pageSize);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //根据字段(sort)进行排序,相同再按照修改时间排序
        queryWrapper.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        //调用业务层进行分页查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    /**
     * 修改
     *
     * @param category
     * @return R<String>
     */
    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("分类修改成功");
    }

    /**
     * 根据id删除
     * 删除之前还需要判断该菜品分类是否有相关联的菜品
     *
     * @param id
     * @return R<String>
     */
    @DeleteMapping
    public R<String> delete(Long id) {
        categoryService.remove(id);
        return R.success("菜品分类删除成功");
    }

    /**
     * (数据回显)菜品添加功能表中菜品分类下拉框
     *
     * @param category
     * @return R<List < Category>>
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件,type不为空,菜品相等,默认都是1
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        //排序,先按照sort大小,相等再按照修改时间
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        //分装进集合
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }

}
